<script setup lang='ts'>
import type { OptionsType } from 'plus-pro-components'

import { useGetAllSupplierTree, useGetEnterpriseInfo, useGetEnterpriseType, useGetServiceCategory, useJcEnterpriseAudit } from '@fl/api/man-api'
import { downTpl } from '@fl/api/man-api/jc-authentication'
import { SearchForm } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import { colProps } from 'element-plus'

const formRef = ref()
const props = { multiple: true }
const { query } = useRoute()
const { go } = useRouter()
const oldValList = ref<any[]>([])
const newValList = ref<any[]>([])
const fileType = '.rar,.zip,.doc,.docx,.pdf,.jpg,.jpeg,.png,.xlsx'

const state = ref<any>({
    accountName: '',
    accountNumber: '',
    attachmentsAuthorizationLetterList: [],
    bankName: '',
    businessLicenseAttachmentsList: [],
    businessPeriod: '',
    cat: [],
    contactCardNo: '',
    contactMobile: '',
    contactName: '',
    enterpriseName: '',
    enterpriseSecondType: '',
    establishmenDate: '',
    legalCard: '',
    legalMobile: '',
    legalRepresentative: '',
    logo: '',
    projectPerformanceList: [],
    qualificationDocumentList: [],
    registeredAddress: '',
    registeredCapital: '',
    supplyCat: '',
    unifiedSocialCreditCode: '',
})

const key = ref(1)
const id = ref(query?.id as string)
const { data: enterpriseInfo, isLoading: isEnterpriseInfo } = useGetEnterpriseInfo(id)
const { data: serviceCategoryOptions, isLoading: isServiceCategoryLoading } = useGetServiceCategory()
const { data: supplierTree } = useGetAllSupplierTree()

const { isPending, mutate } = useJcEnterpriseAudit()
const isLoading = computed(() => isEnterpriseInfo.value || isServiceCategoryLoading.value || isPending.value)

const type = computed(() => Number(state.value.enterpriseType) + 1)

const { data: enterpriseTypeList } = useGetEnterpriseType(type)

const disabled = computed(() => true)
const changeBusinessLicenseAttachmentsList = ref(false)
const changeAttachmentsAuthorizationLetterList = ref(false)
const isAudit = computed(() => Number(state.value.auditStatus) === 0)
const rejectedVisible = ref(false)

const rejectedForm = ref({
    auditRemark: '',
})
const rejectedColumns: any[] = [
    {
        colProps: {
            span: 24,
        },
        fieldProps: {
            maxlength: 500,
        },
        label: '驳回原因',
        prop: 'auditRemark',
        valueType: 'textarea',

    },
]
const rejectedrules = {
    auditRemark: [
        {
            message: '请输入驳回原因',
            required: true,
        },
    ],
}
const finalGroup: any = computed(() => {
    return [
        {
            columns: [
                {
                    colProps: {
                        span: 24,
                    },
                    hasLabel: false,
                    label: '变更信息',
                    prop: 'changeInformation',
                },

            ],
            hideInGroup: computed(() => !isAudit.value),
            title: '变更信息',
        },
        {
            columns: [
                {
                    fieldProps: {
                        disabled: true,
                    },
                    label: '统一社会信用代码',
                    prop: 'unifiedSocialCreditCode',
                    valueType: 'input',
                },
                {

                    fieldProps: {
                        disabled,
                    },
                    label: '公司名称',
                    prop: 'enterpriseName',
                    valueType: 'input',
                },
                {

                    fieldProps: {
                        disabled,
                    },
                    label: '法定代表人',
                    prop: 'legalRepresentative',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '成立日期',
                    prop: 'establishmenDate',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '营业期限',
                    prop: 'businessPeriod',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '注册资本',
                    prop: 'registeredCapital',
                    valueType: 'input',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '企业LOGO',
                    prop: 'logo',

                },
                {
                    colProps: {
                        span: 24,
                    },
                    fieldProps: {
                        disabled,
                    },
                    label: '注册地址',
                    prop: 'registeredAddress',
                    valueType: 'input',
                },

            ],
            title: '工商信息(数据来源于企查查)',
        },
        {
            columns: [
                {
                    colProps: {
                        span: 24,
                    },
                    fieldProps: { disabled, props },
                    label: '服务类别',
                    options: serviceCategoryOptions as OptionsType,
                    prop: 'cat',
                    valueType: 'cascader',
                },

            ],
            hideInGroup: computed(() => query?.source !== 'manufacturer'),
            title: '产品服务',
        },
        {
            columns: [
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '姓名',
                    prop: 'legalRepresentative',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '电话',
                    prop: 'legalMobile',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '身份证号码',
                    prop: 'legalCard',
                    valueType: 'input',
                },
            ],
            title: '法人信息',
        },
        {
            columns: [
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '姓名',
                    prop: 'contactName',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '电话',
                    prop: 'contactMobile',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '身份证号码',
                    prop: 'contactCardNo',
                    valueType: 'input',
                },
            ],
            title: '联系人信息',
        },
        {
            columns: [
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '开户名',
                    prop: 'accountName',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '开户行',
                    prop: 'bankName',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '银行账号',
                    prop: 'accountNumber',
                    valueType: 'input',
                },
            ],
            title: '账户信息',
        },
        {
            columns: [
                {
                    fieldProps: {
                        disabled,
                    },
                    label: computed(() => {
                        return Number(state.value.enterpriseType) === 0 ? `采购商类型` : `供应商类型`
                    }),

                    options: computed(() => {
                        return enterpriseTypeList.value || []
                    }),
                    prop: 'enterpriseSecondType',
                    valueType: 'select',
                    width: 120,
                },
                {

                    fieldProps: {
                        disabled,
                        props: {
                            multiple: true,

                        },
                        showAllLevels: false,
                    },
                    hideInForm: computed(() => !(Number(state.value.enterpriseType) === 1)),
                    label: '供应商类别',
                    options: computed(() => {
                        return supplierTree.value || []
                    }),
                    prop: 'supplyCat',
                    valueType: 'cascader',
                    width: 120,
                },

            ],
            title: '机构类型',
        },
        {
            columns: [
                {
                    colProps: {
                        span: 24,
                    },
                    label: '营业执照附件',
                    prop: 'businessLicenseAttachmentsList',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '授权函',
                    prop: 'attachmentsAuthorizationLetterList',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '资质文件',
                    prop: 'qualificationDocumentList',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '项目业绩',
                    prop: 'projectPerformanceList',
                },
            ],
            title: '附件信息(仅修改企业信息上传)',
        },
    ]
})

watchEffect(() => {
    if (enterpriseInfo.value) {
        const businessLicenseAttachmentsList = enterpriseInfo.value.jcEnterpriseInfoPart.businessLicenseAttachmentsList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        const attachmentsAuthorizationLetterList = enterpriseInfo.value.jcEnterpriseInfoPart.attachmentsAuthorizationLetterList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        const qualificationDocumentList = enterpriseInfo.value.jcEnterpriseInfoPart.qualificationDocumentList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        const projectPerformanceList = enterpriseInfo.value.jcEnterpriseInfoPart.projectPerformanceList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        state.value = {
            ...enterpriseInfo.value.jcEnterpriseInfoPart,
            attachmentsAuthorizationLetterList,
            businessLicenseAttachmentsList,
            cat: enterpriseInfo.value.jcEnterpriseInfoPart?.cat && JSON.parse(enterpriseInfo.value.jcEnterpriseInfoPart?.cat),
            enterpriseSecondType: `${enterpriseInfo.value.jcEnterpriseInfoPart?.enterpriseSecondType}`,
            logo: enterpriseInfo.value.jcEnterpriseInfoPart?.logo || '',
            projectPerformanceList,
            qualificationDocumentList,
            supplyCat: enterpriseInfo.value.jcEnterpriseInfoPart?.supplyCat ? JSON.parse(enterpriseInfo.value.jcEnterpriseInfoPart?.supplyCat) : [],
        }
        oldValList.value = []
        newValList.value = []
        if (enterpriseInfo.value.changeInfoVOList) {
            const { newList, oldList } = formatList(enterpriseInfo.value.changeInfoVOList || [])
            oldValList.value = oldList
            newValList.value = newList
        }
        key.value++
    }
})

function sumbit() {
    const params = {
        auditStatus: 1,
        enterpriseId: unref(id),
    }
    audit(params)
}

function rejectedSubmit() {
    const params = {
        auditRemark: unref(rejectedForm).auditRemark,
        auditStatus: 2,
        enterpriseId: unref(id),
    }
    audit(params)
}
function rejectedCancel() {
    unref(rejectedForm).auditRemark = ''
}
function audit(params: any) {
    mutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
            unref(rejectedForm).auditRemark = ''
            rejectedVisible.value = false
        },
    })
}
function goback() {
    go(-1)
}

function formatList(arr: any[]) {
    const oldList: any[] = []
    const newList: any[] = []

    arr.forEach((item: any) => {
        if (item.name === '营业执照附件列表' || item.name === '授权函附件列表' || item.name === '资质文件文件列表' || item.name === '项目业绩文件列表') {
            console.log(item, 'item')

            oldList.push({
                name: item.name,
                value: item.oldValue ? [{ name: item.oldValue.fileName || item.oldValue.name, url: item.oldValue.fileUrl || item.oldValue.url }] : [],
            })
            newList.push({
                name: item.name,
                value: item.newValue ? [{ name: item.newValue.fileName || item.newValue.name, url: item.newValue.fileUrl || item.newValue.url }] : [],
            })
        }
        else {
            oldList.push({
                name: item.name,
                value: item.oldValue,
            })
            newList.push({
                name: item.name,
                value: item.newValue,
            })
        }
    })

    return { newList, oldList }
}

defineExpose({
    state,
})
</script>

<template>
    <ElCard shadow="never">
        <div class="mb-20 text-16 font-700">
            企业信息
        </div>

        <SearchForm ref="formRef"
                    v-model="state"
                    :group="finalGroup"
                    submit-text="查询"
                    :has-footer="false"
                    label-position="top"
        >
            <template #plus-field-changeInformation>
                <div class="w-full">
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <div class="old p-16 bg-#f7f8fa h-full">
                                <el-descriptions :column="1">
                                    <template #title>
                                        <div class="flex gap-5 items-center">
                                            <el-icon :size="20"
                                                     style="color:#86909C"
                                            >
                                                <InfoFilled />
                                            </el-icon>
                                            原信息
                                        </div>
                                    </template>

                                    <el-descriptions-item v-for="(item, index) in oldValList"
                                                          :key="index"
                                                          :label="`${item.name} :`"
                                    >
                                        <template v-if="item.name === '企业logo'">
                                            <FlUpload :key="key"
                                                      v-model="item.value"
                                                      tips
                                                      accept=".jpg,.jpeg,.png"
                                                      :disabled="disabled"
                                                      is-mall-admin
                                            />
                                        </template>

                                        <template v-else-if="item.name === '营业执照附件列表' || item.name === '授权函附件列表' || item.name === '资质文件文件列表' || item.name === '项目业绩文件列表'">
                                            <div class="truncate">
                                                <FlUpload :key="key"
                                                          v-model="item.value"
                                                          list-type="text"
                                                          is-mall-admin
                                                          :disabled="disabled"
                                                />
                                            </div>
                                        </template>

                                        <template v-else>
                                            {{ item.value }}
                                        </template>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </div>
                        </el-col>

                        <el-col :span="8">
                            <div class="new p-16 bg-#F0FFF0 h-full">
                                <el-descriptions :column="1">
                                    <template #title>
                                        <div class="flex gap-5 items-center">
                                            <el-icon :size="20"
                                                     style="color:#3BB346;"
                                            >
                                                <SuccessFilled />
                                            </el-icon>
                                            变更为
                                        </div>
                                    </template>

                                    <el-descriptions-item v-for="(item, index) in newValList"
                                                          :key="index"
                                                          :label="`${item.name} :`"
                                    >
                                        <template v-if="item.name === '企业logo'">
                                            <FlUpload :key="key"
                                                      v-model="item.value"
                                                      tips
                                                      accept=".jpg,.jpeg,.png"
                                                      :disabled="disabled"
                                                      is-mall-admin
                                            />
                                        </template>

                                        <template v-else-if="item.name === '营业执照附件列表' || item.name === '授权函附件列表' || item.name === '资质文件文件列表' || item.name === '项目业绩文件列表'">
                                            <div class="truncate">
                                                <FlUpload :key="key"
                                                          v-model="item.value"
                                                          list-type="text"
                                                          is-mall-admin
                                                          :disabled="disabled"
                                                />
                                            </div>
                                        </template>

                                        <template v-else>
                                            {{ item.value }}
                                        </template>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </template>

            <template #group-header="{ title, icon }">
                <div>
                    <div v-if="title === '工商信息(数据来源于企查查)' "
                         class="p-5 bg-#fcf6ed leading-[32px]"
                    >
                        {{ state.auditStatusName }}

                        <div v-if="state.auditStatus === 2 && state.auditRemark">
                            驳回原因: {{ state.auditRemark }}
                        </div>
                    </div>

                    <span class="leading-[32px]">
                        {{ title }}
                        <el-icon> <component :is="icon" /> </el-icon>
                    </span>
                </div>
            </template>

            <template #plus-field-logo>
                <FlUpload :key="key"
                          v-model="state.logo"
                          tips
                          accept=".jpg,.jpeg,.png"
                          :disabled="disabled"
                          is-mall-admin
                />
            </template>

            <template #plus-field-businessLicenseAttachmentsList>
                <div flex
                     flex-col
                     w-full
                >
                    <FlUpload :key="key"
                              v-model="state.businessLicenseAttachmentsList"
                              list-type="text"
                              :limit="1"
                              :file-size="10"
                              :accept="fileType"
                              is-mall-admin
                              :disabled="disabled"
                              @success="changeBusinessLicenseAttachmentsList = true"
                    />

                    <div class="text-14 c-#86909C cursor-pointer">
                        最多上传一张
                    </div>
                </div>
            </template>

            <template #plus-field-attachmentsAuthorizationLetterList>
                <div flex
                     flex-col
                     w-full
                >
                    <FlUpload :key="key"
                              v-model="state.attachmentsAuthorizationLetterList"
                              list-type="text"
                              :limit="5"
                              :file-size="10"
                              :accept="fileType"
                              tips
                              is-mall-admin
                              :disabled="disabled"
                              @success="changeAttachmentsAuthorizationLetterList = true"
                    />

                    <div class="text-14 c-#86909C cursor-pointer"
                         @click="downTpl('授权函模板')"
                    >
                        <span class="c-#EA0000">下载</span>《授权函模板》
                    </div>
                </div>
            </template>

            <template #plus-field-qualificationDocumentList>
                <FlUpload :key="key"
                          v-model="state.qualificationDocumentList"
                          list-type="text"
                          :limit="5"
                          :file-size="10"
                          :accept="fileType"
                          tips
                          is-mall-admin
                          :disabled="disabled"
                />
            </template>

            <template #plus-field-projectPerformanceList>
                <FlUpload :key="key"
                          v-model="state.projectPerformanceList"
                          list-type="text"
                          :limit="5"
                          :file-size="10"
                          :accept="fileType"
                          tips
                          is-mall-admin
                          :disabled="disabled"
                />
            </template>
        </SearchForm>

        <template #footer>
            <div class="flex justify-center">
                <el-button type="info"
                           @click="goback"
                >
                    返回
                </el-button>

                <template v-if="isAudit">
                    <el-button type="primary"
                               @click="rejectedVisible = true"
                    >
                        驳回
                    </el-button>

                    <el-button type="primary"
                               :loading="isLoading"
                               @click="sumbit"
                    >
                        通过
                    </el-button>
                </template>
            </div>
        </template>
    </ElCard>

    <PlusDialogForm v-model:visible="rejectedVisible"
                    v-model="rejectedForm"
                    :form="{ columns: rejectedColumns, rules: rejectedrules, labelPosition: 'top' }"
                    @confirm="rejectedSubmit"
                    @cancel="rejectedCancel"
    />
</template>

<style lang="scss" scoped>
:deep(.logo-upload) {
    .el-upload {
        width: 100%;
    }
}

:deep(.el-card__header .leading-\[32px\]) {
    font-weight: 600;
}

.old :deep(.el-descriptions__body .el-descriptions__table) {
    background: #f7f8fa;
}

.new :deep(.el-descriptions__body .el-descriptions__table) {
    background: #f0fff0;
}

:deep(.el-descriptions__body) {
    overflow: hidden;
}
</style>
